package com.hotswap.action;

import com.hotswap.dialog.MyToolWindow;
import com.hotswap.domain.AppSettingsState;
import com.hotswap.domain.ClassInfo;
import com.hotswap.utils.*;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.project.Project;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.net.URLEncoder;

public class SwapClassAction extends AnAction {

    private static final String CHARSET_NAME = "UTF-8";

    private String remoteUrl = "https://judata.alibaba-inc.com/hotSwap.htm";

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        DataContext dataContext = event.getDataContext();
        Project project = dataContext.getData(CommonDataKeys.PROJECT);
        try {
            ClassInfo currentClassInfo = ClassUtils.parseClassInfoFromDataContext(dataContext);
            String code = FileUtils.readFileToString(new File(currentClassInfo.getClassPath()), CHARSET_NAME);
            if (code == null) {
                NotifyUtils.error(project,
                        "Please compile the file first ! "
                                + "\nCan't find the class of the source file : " + currentClassInfo.getClassPath());
                return;
            }
            AppSettingsState settings = AppSettingsState.getInstance(project);
            StringBuilder builder = new StringBuilder();
            StringUtils.putRequestBody(builder, "code", URLEncoder.encode(AppUtils.delombok(code), "UTF-8"));
            StringUtils.putRequestBody(builder, "hosts", settings.hosts);
            MyToolWindow.consoleLog(HttpUtils.httpPost(remoteUrl, builder.toString()));
        } catch (Exception t) {
            MyToolWindow.consoleLog(IoUtils.printStackTrace(t));
        }
    }

}
